<template>
  <div class="event-container">
    <div class="event-header">
      <h2>赛事管理</h2>
      <div class="header-buttons">
        <el-button type="primary" @click="handleGenerateOrder">生成秩序册</el-button>
        <el-button type="primary" @click="handleAdd">录入赛事</el-button>
      </div>
    </div>

    <!-- 赛事列表 -->
    <el-table :data="eventList" v-loading="loading" border>
      <el-table-column prop="name" label="赛事名称" />
      <el-table-column prop="startTime" label="开始时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="rules" label="规则" show-overflow-tooltip />
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '修改赛事' : '录入赛事'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="赛事名称" prop="name">
          <el-input v-model="form.name" placeholder="如：100米跑、跳远等" />
        </el-form-item>
        <el-form-item label="时间范围" prop="timeRange">
          <el-date-picker
            v-model="form.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="规则" prop="rules">
          <el-input 
            v-model="form.rules" 
            type="textarea"
            rows="3"
            placeholder="请输入比赛规则"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 项目管理对话框 -->
    <el-dialog
      v-model="itemsDialogVisible"
      title="比赛项目管理"
      width="800px"
    >
      <div class="items-header">
        <el-button type="primary" @click="handleAddItem">新增项目</el-button>
      </div>
      
      <el-table :data="itemsList" border>
        <el-table-column prop="name" label="项目名称" />
        <el-table-column prop="type" label="项目类型" />
        <el-table-column prop="maxParticipants" label="最大参与人数" width="120" />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEditItem(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDeleteItem(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 项目编辑对话框 -->
      <el-dialog
        v-model="itemFormVisible"
        :title="itemDialogTitle"
        width="500px"
        append-to-body
      >
        <el-form
          ref="itemFormRef"
          :model="itemForm"
          :rules="itemRules"
          label-width="100px"
        >
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="itemForm.name" />
          </el-form-item>
          <el-form-item label="项目类型" prop="type">
            <el-select v-model="itemForm.type" style="width: 100%">
              <el-option label="田赛" value="field" />
              <el-option label="径赛" value="track" />
            </el-select>
          </el-form-item>
          <el-form-item label="最大人数" prop="maxParticipants">
            <el-input-number 
              v-model="itemForm.maxParticipants" 
              :min="1"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input 
              v-model="itemForm.description" 
              type="textarea"
              rows="3"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="itemFormVisible = false">取消</el-button>
            <el-button 
              type="primary" 
              @click="handleItemSubmit"
              :loading="itemSubmitting"
            >
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 列表相关
const loading = ref(false)
const eventList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 模拟数据
const fetchData = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    eventList.value = [
      {
        id: 1,
        name: '100米跑',
        startTime: '2024-04-01 09:00:00',
        endTime: '2024-04-01 12:00:00',
        rules: '1. 遵守比赛规则\n2. 按时到场\n3. 听从裁判指挥'
      }
    ]
    total.value = 1
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 新增/编辑相关
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref(null)
const form = reactive({
  id: '',
  name: '',
  timeRange: [],
  rules: ''
})

const rules = {
  name: [{ required: true, message: '请输入赛事名称', trigger: 'blur' }],
  timeRange: [{ required: true, message: '请选择时间范围', trigger: 'change' }],
  rules: [{ required: true, message: '请输入比赛规则', trigger: 'blur' }]
}

const handleAdd = () => {
  form.id = ''
  form.name = ''
  form.timeRange = []
  form.rules = ''
  dialogVisible.value = true
}

const handleEdit = (row) => {
  form.id = row.id
  form.name = row.name
  form.timeRange = [row.startTime, row.endTime]
  form.rules = row.rules
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        await new Promise(resolve => setTimeout(resolve, 1000))
        ElMessage.success(form.id ? '修改成功' : '录入成功')
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        ElMessage.error(form.id ? '修改失败' : '录入失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 项目管理相关
const itemsDialogVisible = ref(false)
const itemsList = ref([])
const currentEventId = ref(null)

const handleManageItems = (row) => {
  currentEventId.value = row.id
  itemsDialogVisible.value = true
  fetchItems()
}

// 模拟获取项目列表
const fetchItems = async () => {
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    itemsList.value = [
      {
        id: 1,
        name: '100米跑',
        type: 'track',
        maxParticipants: 8
      }
    ]
  } catch (error) {
    ElMessage.error('获取项目列表失败')
  }
}

// 项目表单相关
const itemFormVisible = ref(false)
const itemDialogTitle = ref('')
const itemSubmitting = ref(false)
const itemFormRef = ref(null)
const itemForm = reactive({
  name: '',
  type: '',
  maxParticipants: 1,
  description: ''
})

const itemRules = {
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择项目类型', trigger: 'change' }
  ],
  maxParticipants: [
    { required: true, message: '请输入最大人数', trigger: 'blur' }
  ]
}

const resetItemForm = () => {
  itemForm.id = undefined
  itemForm.name = ''
  itemForm.type = ''
  itemForm.maxParticipants = 1
  itemForm.description = ''
}

const handleAddItem = () => {
  itemDialogTitle.value = '新增项目'
  resetItemForm()
  itemFormVisible.value = true
}

const handleEditItem = (row) => {
  itemDialogTitle.value = '编辑项目'
  Object.assign(itemForm, row)
  itemFormVisible.value = true
}

const handleItemSubmit = async () => {
  if (!itemFormRef.value) return
  
  await itemFormRef.value.validate(async (valid) => {
    if (valid) {
      itemSubmitting.value = true
      try {
        await new Promise(resolve => setTimeout(resolve, 1000))
        ElMessage.success(itemForm.id ? '修改成功' : '添加成功')
        itemFormVisible.value = false
        fetchItems()
      } catch (error) {
        ElMessage.error(itemForm.id ? '修改失败' : '添加失败')
      } finally {
        itemSubmitting.value = false
      }
    }
  })
}

const handleDeleteItem = (row) => {
  ElMessageBox.confirm(
    '确定要删除该项目吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      ElMessage.success('删除成功')
      fetchItems()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return date
}

// 生成秩序册
const handleGenerateOrder = async () => {
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('秩序册生成成功')
  } catch (error) {
    ElMessage.error('秩序册生成失败')
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.event-container {
  padding: 20px;
}

.event-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.items-header {
  margin-bottom: 20px;
}
</style> 